<!--
 * @Author: Seon.Hu SeonHu@126.com
 * @Date: 2023-06-16 15:13:22
 * @LastEditors: Seon.Hu SeonHu@126.com
 * @LastEditTime: 2023-11-27 16:07:41
 * @FilePath: \bg-vben\src\components\Captcha\src\CaptchaImg.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <img
    v-bind="$attrs"
    :src="formData.imageSrc"
    @click="handleStart"
    :preview="false"
    :alt="t('component.captcha.image')"
    fallback=""
    style="cursor: pointer"
  />
</template>
<script lang="ts" setup>
  import { reactive, PropType, watchEffect } from 'vue';

  // import { Image } from 'ant-design-vue';

  import { isFunction } from '@/utils/is';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useRuleFormItem } from '@/hooks/component/useFormItem';

  defineOptions({ name: 'CaptchaImg' });
  const props = defineProps({
    value: { type: String },
    beforeStartFunc: {
      type: Function as PropType<() => Promise<string>>,
      default: null,
    },
  });

  const { t } = useI18n();

  const formData = reactive({
    imageSrc: '',
  });

  watchEffect(async () => {
    const { beforeStartFunc } = props;
    if (beforeStartFunc && isFunction(beforeStartFunc)) {
      formData.imageSrc = await beforeStartFunc();
    }
  });

  useRuleFormItem(props);

  /**
   * @description: 执行前判断是否有外部功能，执行后决定是否启动（Judge whether there is an external function before execution, and decide whether to start after execution）
   */
  async function handleStart() {
    const { beforeStartFunc } = props;
    if (beforeStartFunc && isFunction(beforeStartFunc)) {
      try {
        formData.imageSrc = await beforeStartFunc();
      } catch {
        formData.imageSrc = '';
      }
    }
  }
</script>
